package yl.hs.bmipfull.service.system.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import yl.hs.bmipfull.daos.system.*;
import yl.hs.bmipfull.daos.vehiclemanage.ITruckInfoDao;
import yl.hs.bmipfull.pojo.system.AppSettingEntity;
import yl.hs.bmipfull.pojo.system.AreaEntity;
import yl.hs.bmipfull.pojo.system.SiteMessageMainEntity;
import yl.hs.bmipfull.pojo.system.SiteMessageReceiptEntity;
import yl.hs.bmipfull.pojo.vehiclemanage.TruckInfoEntity;
import yl.hs.bmipfull.service.impl.BaseService;
import yl.hs.bmipfull.service.system.IActiveService;
import yl.hs.bmipfull.utils.*;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.ActiveDeviceType;
import yl.hs.bmipfull.viewmodels.WebReceiveVO;
import yl.hs.bmipfull.viewmodels.system.ActiveStateModel;
import yl.hs.bmipfull.viewmodels.system.BlueAreaData;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/*
 * ActiveServiceImpl
 * @category
 * @author 谢景广
 * @date 2022-05-11
 */
@Service
public class ActiveServiceImpl extends BaseService implements IActiveService {

    @Value("${swagger.enable}")
    public boolean DevMode;

    @Override
    public int active(String code, ActiveDeviceType type) throws Exception {
        var st = settingDao.findBlueArea(ActiveDeviceType.getTypeKey(type));
        if (st == null) {
            st = initActiveInfo(type);
            if (st == null) {
                return 0;
            }
        }
        var oldData = BlueAreaData.parse(st.getParamStream());
        BlueAreaData newData = null;
        try {
            newData = BlueAreaData.parse(code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (newData == null) {
            return 0;
        }
        if (newData.validActiveSN(oldData.getActiveSN())
                && newData.getMachineCode().equals(MachineUtils.makeMachineCode(type))) {
            st.setParamStream(newData.toStream());
            st.setParamValue(Tl.getDateString(new Date()));
            return settingDao.update(st);
        } else {
            throw new RuntimeException("无效的激活码，机器码错误");
        }
    }

    private AppSettingEntity initActiveInfo(ActiveDeviceType type) {
        try {
            var org = orgDao.findRootUnit();
            var activeData = new BlueAreaData(type);
            var st = new AppSettingEntity();
            st.setParamValue(activeData.getRandomCode());
            st.setParamName("ImportantData");
            st.setParamCode(ActiveDeviceType.getTypeKey(type));
            st.setParamStream(activeData.toStream());
            st.setOrganizationSN(org.getSn());
            //HsApp.getCurrent().getOrganizationCode()
            settingDao.insertNew(st);
            return st;
        } catch (Exception ee) {
            ee.printStackTrace();
            return null;
        }
    }

    @Override
    public ActiveStateModel getAvailableDays(ActiveDeviceType type) throws Exception {
        if (DevMode) {
            return new ActiveStateModel(99, "开发模式");
        }
        var st = settingDao.findBlueArea(ActiveDeviceType.getTypeKey(type));
        if (st != null) {
            var activeData = BlueAreaData.parse(st.getParamStream());
            if (activeData != null) {
                if (!activeData.getMachineCode().equals(MachineUtils.makeMachineCode(type))) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(new Date());
                    cal.add(Calendar.DATE, 3);
                    activeData.setEndTime(Tl.getDateString(cal.getTime(), "yyyy-MM-dd"));
                    activeData.setMachineCode(MachineUtils.makeMachineCode(type));
                    activeData.setState("设备变更");
                    st.setParamStream(activeData.toStream());
                    settingDao.update(st);
                    return new ActiveStateModel(3, "设备变更");
                }
                var endDate = Tl.strToDate(activeData.getEndTime(), "yyyy-MM-dd");
                Calendar cal = Calendar.getInstance();
                cal.setTime(endDate);
                cal.add(Calendar.DATE, 1);
                var endTime = cal.getTime().getTime();
                var nowTime = new Date().getTime();
                var timeSpan = endTime - nowTime;
                if (timeSpan > 0) {
                    var days = Integer.parseInt((timeSpan / (24 * 60 * 60 * 1000)) + "");
                    return new ActiveStateModel(days, activeData.getState());
                } else {
                    return new ActiveStateModel(0, "正常");
                }
            } else {
                return new ActiveStateModel(0, "激活信息被变更");
            }
        } else {
            var result = initActiveInfo(type);
            if (result != null) {
                return new ActiveStateModel(3, "初次激活");
            } else {
                return new ActiveStateModel(0, "未初始化");
            }
        }
    }


    @Override
    @Scheduled(cron = "0 0 9 * * ?")
    public int onlineActive() {
        try {

            var map = createActiveParam(ActiveDeviceType.ERPPC);
            if (map == null)
                return 0;
            var result = WebUtil.ActiveRequest(CK.Active_Server + "/erp/activation", map);
            var webResult = Tl.toObject(result, WebReceiveVO.class);
            if (webResult != null) {
                if (!Tl.isEmpty(webResult.getData())) {
                    return active(webResult.getData(), ActiveDeviceType.ERPPC);
                }
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }
        return 0;
    }

    private Map<String, Object> createActiveParam(ActiveDeviceType type) {
        var org = orgDao.findRootUnit();
        var versionName = settingDao.getByCodeAndUnitSN(CK.SysVersionName, org.getSn());
        var version = settingDao.getByCodeAndUnitSN(CK.SysVersion, org.getSn());
        var sUser = settingDao.getByCodeAndUnitSN(CK.Service_User, org.getSn());
        if (org == null) {
            return null;
        }
        var map = new HashMap<String, Object>();
        map.put("companyCode", org.getSn());
        map.put("deviceType", type.dataCode);
        map.put("companyName", org.getFullName());
        var vName = CK.getVersionName(version.getParamValue());
        map.put("systemVersion", versionName == null ? "华砂智慧商砼ERP综合管理系统" : versionName.getParamValue() + "-" + vName);
        map.put("attendant", sUser == null ? "" : sUser.getParamValue());
        map.put("unitType", org.getOrganizationType());
        map.put("computerCode", MachineUtils.makeMachineCode(type));
        map.put("macs", MachineUtils.getMacs());
        return map;
    }

    /**
     * ERP 手机端激活
     */
    @Override
    @Scheduled(cron = "10 5 9 * * ?")
    public void onlineERPMobileActive() {
        try {
            var map = createActiveParam(ActiveDeviceType.ERPMobile);
            var result = WebUtil.ActiveRequest(CK.Active_Server + "/erp/activation", map);
            var webResult = Tl.toObject(result, WebReceiveVO.class);
            if (webResult != null) {
                if (!Tl.isEmpty(webResult.getData())) {
                    active(webResult.getData(), ActiveDeviceType.ERPMobile);
                }
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    /**
     * 经销商端激活
     */
    @Override
    @Scheduled(cron = "20 10 9 * * ?")
    public void onlineDealerActive() {
        try {
            var map = createActiveParam(ActiveDeviceType.Dealer);
            var result = WebUtil.ActiveRequest(CK.Active_Server + "/erp/activation", map);
            var webResult = Tl.toObject(result, WebReceiveVO.class);
            if (webResult != null) {
                if (!Tl.isEmpty(webResult.getData())) {
                    active(webResult.getData(), ActiveDeviceType.Dealer);
                }
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    /**
     * 工地端激活
     */
    @Override
    @Scheduled(cron = "30 15 9 * * ?")
    public void onlineConstructionActive() {
        try {
            var map = createActiveParam(ActiveDeviceType.Construction);
            var result = WebUtil.ActiveRequest(CK.Active_Server + "/erp/activation", map);
            var webResult = Tl.toObject(result, WebReceiveVO.class);
            if (webResult != null) {
                if (!Tl.isEmpty(webResult.getData())) {
                    active(webResult.getData(), ActiveDeviceType.Construction);
                }
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    /**
     * 供应商端激活
     */
    @Override
    @Scheduled(cron = "40 20 9 * * ?")
    public void onlineSupplierActive() {
        try {
            var map = createActiveParam(ActiveDeviceType.Supplier);
            var result = WebUtil.ActiveRequest(CK.Active_Server + "/erp/activation", map);
            var webResult = Tl.toObject(result, WebReceiveVO.class);
            if (webResult != null) {
                if (!Tl.isEmpty(webResult.getData())) {
                    active(webResult.getData(), ActiveDeviceType.Supplier);
                }
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    /**
     * 司机端激活
     */
    @Override
    @Scheduled(cron = "50 25 9 * * ?")
    public void onlineDriverActive() {
        try {
            var map = createActiveParam(ActiveDeviceType.Driver);
            var result = WebUtil.ActiveRequest(CK.Active_Server + "/erp/activation", map);
            var webResult = Tl.toObject(result, WebReceiveVO.class);
            if (webResult != null) {
                if (!Tl.isEmpty(webResult.getData())) {
                    active(webResult.getData(), ActiveDeviceType.Driver);
                }
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }

    @Override
    @Scheduled(cron = "55 30 9 * * ?")
    public void saveCarNews() {
        try {
            var org = orgDao.findRootUnit();
            String unitSN = org.getSn();
            var setting = appSetDao.queryAll(unitSN.split(","));
            var result = setting.stream().filter(t -> t.getParamCode().equals("CarCaptainSN")).toList();
            if (result != null && result.size() > 0) {
                var userinfo = userInfoDao.findBySN(result.get(0).getParamValue());
                if (userinfo != null) {
                    var carlist = truckInfoDao.queryList(null, null);
                    var nowTime = new Date().getTime();
                    for (TruckInfoEntity s : carlist) {
                        if(s.getExpiryDateOfInsurance()==null){
                            continue;
                        }
                        var endTime = s.getExpiryDateOfInsurance().getTime();
                        var timeSpan = endTime - nowTime;
                        var days = Integer.parseInt((timeSpan / (24 * 60 * 60 * 1000)) + "");
                        if (days <= 30) {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String currentSimpleDateFormat = simpleDateFormat.format(s.getExpiryDateOfInsurance());
                            var main = new SiteMessageMainEntity();
                            main.setSn(queryNewSN(SiteMessageMainEntity.class));
                            main.setMsgBody("车辆【" + s.getTruckPlate() + "】【"+s.getInsuranceType()+"】将于【" + currentSimpleDateFormat + "】到期，请提前购买！");
                            main.setSenderSN("USER210429000001");
                            main.setSerderName("系统机器人");
                            main.setSerderNamePY("xitongjiqiren");
                            main.setSubject("车辆保险提醒");
                            main.setMsgType((short) 0);
                            main.setSendTime(new Date());
                            main.setSubjectPY("cheliangbaoxiantixing");
                            messageMainDao.insertNew(main);
                            var receipt = new SiteMessageReceiptEntity();
                            receipt.setMsgSN(main.getSn());
                            receipt.setReceipterName(userinfo.getNickname());
                            receipt.setReceipterSN(userinfo.getSn());
                            receipt.setReceiptTime(new Date());
                            receipt.setReceiptType((short)100);
                            messageReceiptDao.insertNew(receipt);
                        }
                    };
                }
            }
        } catch (Exception ee) {
               System.out.println(ee);
        }
    }

    @Autowired
    IAppSettingDao settingDao;
    @Autowired
    IOrganizationInfoDao orgDao;
    @Autowired
    ISiteMessageMainDao messageMainDao;
    @Autowired
    ISiteMessageReceiptDao messageReceiptDao;
    @Autowired
    IAppSettingDao appSetDao;
    @Autowired
    ITruckInfoDao truckInfoDao;
    @Autowired
    IUserInfoDao userInfoDao;
}
